#!/bin/bash

install_dir=$HOME
sdk_dir=$install_dir/android-sdk
cmake_dir=$sdk_dir/cmake
ndk_dir="$sdk_dir/ndk"
ndk_file_name="ollvm_ndk_r25c.tar.xz"
ndk_url="https://ghproxy.net/https://github.com/Party233/DexVMP/releases/download/android-ndk-r25c-ollvm/$ndk_file_name"
ndk_installed=false
cmake_installed=false

run_install_cmake() {
    download_cmake 3.10.2
    download_cmake 3.18.1
    download_cmake 3.22.1
    download_cmake 3.25.1
}

download_cmake() {
    cmake_version=$1
    cmake_path="$cmake_dir/$cmake_version"
    
    if [ -d "$cmake_path" ]; then
        echo "CMake $cmake_version 已存在，正在删除旧版本..."
        rm -rf "$cmake_path"
    fi
    
    echo "正在下载 CMake $cmake_version..."
    wget https://ghproxy.net/https://github.com/MrIkso/AndroidIDE-NDK/releases/download/cmake/cmake-"$cmake_version"-android-aarch64.zip --no-verbose --show-progress -N
    installing_cmake "$cmake_version"
}

installing_cmake() {
    cmake_version=$1
    cmake_file=cmake-"$cmake_version"-android-aarch64.zip

    if [ -f "$cmake_file" ]; then
        echo "正在解压 CMake $cmake_version..."
        unzip -qq "$cmake_file" -d "$cmake_dir"
        rm "$cmake_file"
        chmod -R +x "$cmake_dir"/"$cmake_version"/bin
        cmake_installed=true
        echo "CMake $cmake_version 安装完成!"
    else
        echo "错误: 找不到 $cmake_file 文件"
    fi
}

install_ndk() {
    echo "正在下载 NDK..."
    wget "$ndk_url" --no-verbose --show-progress -N
    
    if [ -f "$ndk_file_name" ]; then
        echo "正在解压 NDK..."
        mkdir -p "$ndk_dir"
        tar -xf "$ndk_file_name" -C "$ndk_dir"
        rm "$ndk_file_name"
        ndk_installed=true
        echo "NDK 安装完成!"
    else
        echo "错误: 下载 $ndk_file_name 失败"
    fi
}

echo "开始安装 NDK 和 CMake..."
install_ndk

if [ -d "$cmake_dir" ]; then
    cd "$cmake_dir"
    run_install_cmake
else
    mkdir -p "$cmake_dir"
    cd "$cmake_dir"
    run_install_cmake
fi

if [[ $ndk_installed == true && $cmake_installed == true ]]; then
    echo '安装成功完成!'
else
    echo '安装失败: NDK 或 CMake 安装未完成'
    if [ $ndk_installed == false ]; then
        echo " - NDK 安装失败"
    fi
    if [ $cmake_installed == false ]; then
        echo " - CMake 安装失败"
    fi
fi